importClass(android.graphics.Paint);
importClass(android.graphics.Bitmap);

importClass('java.io.FileOutputStream');
importClass('java.io.IOException');
importClass('java.io.InputStream');
importClass('java.net.MalformedURLException');
importClass('java.net.URL');
importClass('java.net.URLConnection');
importClass('java.util.ArrayList');

// log('下载地址' + url);
// log('存储地址' + filePath);
// log(res);

function 检查更新() {
    try {
        //点击检查更新按钮后进行检查更新
        var r = http.get('https://gitee.com/john_han123/tlbb/raw/master/update.json');
        var res = r.body.json();
        var url = res.downloadUrl;
        var filePath = files.join(files.getSdcardPath(), res.fileName);

        url = new URL(url);
        var conn = url.openConnection(); //URLConnection
        var inStream = conn.getInputStream(); //InputStream
        var fs = new FileOutputStream(filePath); //FileOutputStream
        var connLength = conn.getContentLength(); //int
        var buffer = util.java.array('byte', 1024); //byte[]
        var byteSum = 0; //总共读取的文件大小
        var byteRead; //每次读取的byte数

        var r_ = 0;

        最新版本 = Number((res.versionName * 100).toFixed(0)) + Number(res.versionCode);
        本地版本 = Number((app.versionName * 100).toFixed(0)) + Number(app.versionCode);
        if (最新版本 > 本地版本) {
            //有新版本后显示对话框
            var releaseNotes =
                '版本 ' +
                res.versionName +
                '.' +
                res.versionCode +
                '\n' +
                '大小:' +
                (connLength / 1024 / 1024).toFixed(2) +
                'MB\n' +
                '更新日志:\n' +
                res.updateContent;
            dialogs
                .build({
                    title: '发现新版本',
                    content: releaseNotes,
                    positive: '立即下载',
                    negative: '取消',
                    neutral: '到浏览器下载',
                })
                .on('positive', () => {
                    downloadDialog = dialogs
                        .build({
                            title: '下载中...',
                            positive: '后台下载',
                            negative: '取消',
                            progress: {
                                max: (connLength / 1024 / 1024).toFixed(2),
                                showMinMax: true,
                            },
                            autoDismiss: false,
                        })
                        .on('positive', () => {
                            if (downloadDialog.getActionButton('positive') == '后台下载') {
                                downloadDialog ? downloadDialog.dismiss() : null;
                                downloadDialog = null;
                                //悬浮下载进度展示
                                dw = floaty.rawWindow(
                                    <frame id="bg" w="30" h="30">
                                        <frame>
                                            <img id="ok" h="30" w="30" gravity="center" />
                                            <text id="text" color="#ffffff" textSize="12" gravity="center" />
                                        </frame>
                                    </frame>
                                );
                                threads.start(function () {
                                    var bitmap;
                                    while (byteSum / connLength < 1) {
                                        var bitmap = Bitmap.createBitmap(1000, 1000, Bitmap.Config.ARGB_8888);
                                        var canvas = new Canvas(bitmap);
                                        var paint = new Paint();

                                        paint.setARGB(255, 212, 82, 49); //画笔颜色
                                        paint.setStyle(Paint.Style.FILL); //空心样式STROKE
                                        paint.setStrokeWidth(10); //边缘宽度
                                        canvas.drawCircle(500, 500, 500, paint); //绘制外圆

                                        canvas.drawARGB(0, 0, 0, 0);
                                        paint.setARGB(255, 105, 94, 202); //画笔颜色
                                        paint.setStyle(Paint.Style.FILL); //空心样式
                                        paint.setStrokeWidth(10); //边缘宽度
                                        canvas.drawCircle(500, 500, 5 * r_, paint); //绘制内圆

                                        ui.run(function () {
                                            //悬浮按钮
                                            dw.ok.setImageBitmap(bitmap);
                                            dw.text.text(progress + '%');
                                            log('progress=' + progress);
                                            byteSum / connLength >= 1
                                                ? (dw.text.setText('点击\n安装'), (dw.text.textSize = 8))
                                                : null;
                                        });
                                    }
                                });
                                dw.setPosition(200, 200);
                                downloadDialog ? downloadDialog.dismiss() : null;
                                dw.text.on('click', () => {
                                    if (dw.text.getText() == '点击\n安装') {
                                        //检查APK文件是否存在;
                                        if (files.exists(filePath)) {
                                            log(5555);
                                            if (result.code == 0) {
                                                log('Root权限请求成功');
                                                // 在这里继续执行您的代码
                                            } else {
                                                log('Root权限请求失败：' + result.error);
                                            }
                                            let xx = 0;
                                            var result = shell('pm install -r ' + filePath, true); // 调用install函数安装APK
                                            if (result.result == 'Success\n') {
                                                toastLog('安装完成');
                                                dw.close();
                                            }
                                        } else {
                                            console.error('APK文件不存在！');
                                        }
                                    }
                                });
                            } else if (downloadDialog.getActionButton('positive') == '点击安装') {
                                threads.start(() => {
                                    if (files.exists(filePath)) {
                                        downloadDialog ? downloadDialog.dismiss() : null;
                                        downloadDialog = null;
                                        var result = shell('pm install -r ' + filePath, true); // 调用shell安装APK
                                        if (result.result == 'Success\n') {
                                            toastLog('安装完成');
                                        }
                                    } else {
                                        console.error('APK文件不存在！');
                                    }
                                });
                            } else {
                            }
                        })
                        .on('negative', () => {
                            Download(false);
                            downloadDialog.dismiss();
                            downloadDialog = null;
                        })
                        .show();
                    Download(true);
                    //下载完成
                    threads.start(() => {
                        threads.start(() => {
                            var intervalId = setInterval(() => {
                                if (byteSum / connLength >= 1) {
                                    downloadDialog ? downloadDialog.setActionButton('positive', '点击安装') : null;
                                    clearInterval(intervalId); // 当进度条达到100%时清除定时器
                                }
                            }, 500);
                        });
                    });
                })
                .on('neutral', () => {
                    app.openUrl(res.downloadUrl);
                })
                .show();

            var downloadDialog = null;
            var progress;
            var threadId = threads.start(function () {
                while (1) {
                    var 当前写入的文件大小 = byteSum;
                    progress = (当前写入的文件大小 / connLength) * 100;
                    if (progress > 0.1) {
                        progress = progress.toFixed(0).toString();
                        r_ = progress;
                        if (当前写入的文件大小 >= connLength) {
                            break;
                        }
                    }
                    sleep(1000);
                }
            });
            function Download(YOrN) {
                var aa = 0;
                downloadId = setInterval(() => {
                    if (progress >= 100) {
                        aa++;
                        aa == 1 ? toast('下载完成') : null;
                    } else {
                        downloadDialog ? downloadDialog.setProgress((byteSum / 1024 / 1024).toFixed(2)) : null;
                    }
                }, 100);
                threads.start(() => {
                    try {
                        while ((byteRead = inStream.read(buffer)) != -1) {
                            byteSum += byteRead;
                            //当前时间
                            currentTime = java.lang.System.currentTimeMillis();
                            if (YOrN) {
                                fs.write(buffer, 0, byteRead); //读取
                            } else {
                                break;
                            }
                        }
                        threadId && threadId.isAlive() && threadId.interrupt();
                        toastLog('下载完成');
                    } catch (error) {}
                });
            }
        } else {
            toastLog('已经是最新版本');
        }
    } catch (error) {
        toastLog('检查更新失败，请联系作者');
        console.log(error);
    }
}
// 检查更新();
exports.zxUpdate = 检查更新;
